﻿using MySqlTool;
using System;
using System.Text.Json;


namespace ParkSaleSDK
{
    namespace QuickTool
    {
        public class Helper
        {


            public static object JsonToObject(string json, Type type)
            {
               return  JsonSerializer.Deserialize(json, type);
            }
            public static string ObjectToJson(Object obj)
            {
                return JsonSerializer.Serialize(obj, obj.GetType());
            }
            public static string TimeTOString(DateTime time)
            {
                return $"{time.Year}/{time.Month}/{time.Day} {time.Hour}:{time.Minute}:{time.Second}";
            }
            public static DateTime? StringToTime(string timestring)
            {
                try
                {
                    string[] arr = timestring.Trim().Split('/', ' ', ':');
                    DateTime r = new DateTime(int.Parse(arr[0]), int.Parse(arr[1]), int.Parse(arr[2]), int.Parse(arr[3]), int.Parse(arr[4]), int.Parse(arr[5]));
                    return r;
                }
                catch
                {
                    return null;
                }

            }
        }

        /// <summary>
        /// 选择语句生产器
        /// </summary>
        public sealed class SelectStringMaker
        {
            /// <summary>
            /// 查询表中特定项目的检索命令
            /// </summary>
            /// <param name="table">表名</param>
            /// <param name="targetkey">根据键</param>
            /// <param name="targetvalue">目标键值</param>
            /// <returns></returns>
            public static string MakeSelectStr(string table, string targetkey, string targetvalue)
            {
                return $"SELECT `{table}`.* FROM `{table}` WHERE `{table}`.`{targetkey}` = '{targetvalue}'; ";
            }

            public static string MakeSelectStr(string table,params ValueTuple<string,string>[] conditions)
            {
                string c = "";
                foreach (var i in conditions)
                {
                    string begin = c.Length > 0 ? "AND" : "";
                    c += $" {begin} `{table}`.`{i.Item1}` = '{i.Item2}'";
                }

                return $"SELECT `{table}`.* FROM `{table}` WHERE {c}; ";
            }
            public static string MakeSelectStr(string table, string condition)
            {
                return $"SELECT `{table}`.* FROM `{table}` {condition}; ";
            }
            public static String CountSelectStr(string table, string condition)
            {
                return $"SELECT COUNT(*)  FROM {table} WHERE {condition};";
            }

            public static String CountSelectStr(string table, string key, string value)
            {
                return $"SELECT COUNT(*) FROM `{table}` WHERE `{table}`.`{key}` = '{value}';";
            }

            /// <summary>
            /// 查询整个表的检索命令
            /// </summary>
            /// <param name="table">表名</param>
            /// <returns></returns>
            public static string MakeSelectStr(string table)
            {
                return $"select * from {table}";
            }
        }
    }


    namespace Adapter
    {

        public class c_Any
        {
            public const int m_Any = 9999;
        }
        public class c_OwnedHouse
        {
            public const int m_id = -1, m_location = 0, m_owner = 1, m_house = 2, m_number = 3;
            public const string k_id = "id", k_location = "location", k_owner = "owner", k_house = "house", k_number = "number", Table = "ownedHouse";
        }
        public class c_User
        {

            public const int m_id = -1, m_username = 0, m_Phone = 1, m_Location = 2, m_House = 3, m_Number = 4, m_Password = 5,m_like=6;
            public const string k_ID = "id", k_UserName = "username", k_Password = "password", k_Phone = "phone", k_Location = "location", k_House = "house", k_Number = "number", Table = "User",k_Like="like";
        }
        public class c_Rights
        {
            public const string k_ID = "id", k_Belong = "belong", k_Item = "item", Table = "propertyRight";
            public const int m_id = -1, m_belong = 0, m_Item = 1;
        }
        public class c_Parking
        {
            public const int m_id = -1, m_price = 0, m_Number = 1, m_Location = 2, m_Status = 3, m_Note = 4,m_trait=5;
            public const string k_ID = "id", k_Note = "note", k_Status = "status", k_Location = "location", k_Price = "price", k_Number = "number", Table = "Park",k_Trait="trait";
        }
        public class c_Discount
        {
            public const int m_id = -1, m_code = 0, m_Belong = 1, m_Order = 2, m_PickTime = 3, m_Arg = 4;
            public const string k_ID = "id", k_Code = "code", k_Belong = "belong", k_Order = "order", k_PickTime = "picktime", k_Arg = "arg", Table = "ownedDiscount";
        }
        public class c_Order
        {
            public const int m_id = -1, m_Address = 0, m_Belong = 1, m_Number = 2, m_Time = 3, m_Status = 4, m_Seller = 5, m_Price = 6;
            public const string k_id = "id", k_Address = "address", k_Belong = "belong", k_Number = "number", k_Time = "time", k_Status = "status", k_Seller = "seller", k_Price = "price", Table = "Order";
        }
        public class c_Location
        {
            public const int m_id = -1, m_Name = 0, m_Address = 1, m_Belong = 2, m_longitude=3, m_latitude=4;
            public const string k_id = "id", k_Address = "address", k_Belong = "belong", k_Name = "name", Table = "Location", k_latitude= "latitude", k_longitude= "longitude";
        }
        public class c_Company
        {
            public const int m_id = -1, m_Name = 0, m_About = 1, m_Phone = 2, m_Email = 3, m_Type = 4;
            public const string k_id = "id", k_Name = "name", k_About = "about", k_Phone = "phone", k_Email = "email", k_Type = "type", Table = "Company";
        }
        public class c_Advertisement
        {
            public const int m_id = -1, m_Image = 0, m_Title = 1, m_Belong = 2, m_Url = 3;
            public const string k_id = "id", k_Image = "image", k_Title = "title", k_Belong = "belong", k_Url = "url", Table = "Advertisement";
        }

        public class c_Message
        {
            public const int m_id = -1, m_time = 0, m_content = 1, m_type = 2, m_to = 3, m_from = 4, m_handled = 5, m_arg = 6;
            public const string k_id = "id", k_time = "time", k_content = "content", k_type = "type", k_to = "to", k_from = "from", k_handled = "handled", k_arg = "arg", Table = "Messages";
        }
        /// <summary>
        /// 数据库读取接口
        /// </summary>
        /// <typeparam name="Ttableclass"></typeparam>
        public interface IDatabaseReadable
        {
            /// <summary>
            /// 查询读取
            /// </summary>
            /// <param name="mode">查询模式参数</param>
            /// <param name="value">查询对应值</param>
            /// <returns></returns>
            T[] Find<T>(int mode, string value) where T : new();
        }
        /// <summary>
        /// 数据库读写接口
        /// </summary>
        /// <typeparam name="Ttableclass"></typeparam>
        public interface IDatabaseWriteable<Ttableclass>
        {
            /// <summary>
            /// 向数据库中添加对象
            /// </summary>
            /// <param name="obj"></param>
            /// <returns></returns>
            bool Append(Ttableclass obj);
            /// <summary>
            /// 向数据库中修改对象
            /// </summary>
            /// <param name="target"></param>
            /// <param name="key"></param>
            /// <param name="value"></param>
            /// <returns></returns>
            bool Update(Ttableclass target, string key, string value);

            /// <summary>
            /// 删除数据库中所有查找到的对象
            /// </summary>
            /// <param name="mode">查找模式</param>
            /// <param name="value">查找对应值</param>
            /// <returns></returns>
            bool Delete(int mode, string value);
        }
        /// <summary>
        /// 数据库适配器基类
        /// </summary>
        /// <typeparam name="TablecClass"></typeparam>
        public class DatabaseAdapter
        {
            /// <summary>
            /// 数据库连接字符串
            /// </summary>
            protected string DatabaseConnect
            {
                get;
                set;
            }
            /// <summary>
            /// 表名
            /// </summary>
            protected string TableName
            {
                set;
                get;
            }


            /// <summary>
            /// 初始化
            /// </summary>
            /// <param name="server">服务器</param>
            /// <param name="database">数据库名</param>
            /// <param name="table">表名</param>
            /// <param name="username">用户名</param>
            /// <param name="password">密码</param>
            /// <param name="port">端口</param>
            /// <returns></returns>
            public virtual DatabaseAdapter Init(string server, string database, string table, string username, string password, int port = 3306)
            {
                DatabaseConnect = MySqlManager.ConnectionStr(server, database, username, password, port);
                TableName = table;
                return this;
            }
            /// <summary>
            /// 初始化
            /// </summary>
            /// <param name="connect">链接字符串</param>
            /// <param name="table">表名</param>
            /// <returns></returns>
            public virtual DatabaseAdapter Init(string connect, string table)
            {
                DatabaseConnect = connect;
                this.TableName = table;
                return this;
            }
            protected virtual MySqlManager GetMySqlManager(string command)
            {
                return new MySqlManager() { Connection = new MySql.Data.MySqlClient.MySqlConnection(DatabaseConnect), Table = TableName, CommandText = command };
            }



        }
        /// <summary>
        /// 只读的数据库适配器
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public abstract class ReadableDatabaseAdapter : DatabaseAdapter, IDatabaseReadable
        {
            /// <summary>
            /// 查询命令生成
            /// </summary>
            /// <param name="mode">查询模式</param>
            /// <param name="value">查询对应值</param>
            /// <returns></returns>
            public abstract string FindSelectStr(int mode, string value);
            public T[] Find<T>(int mode, string value = "") where T : new()
            {
                var m = GetMySqlManager(FindSelectStr(mode, value));
                var result = m.Find<T>().ToArray();
                m.Dispose();
                return result;
            }
        }

        /// <summary>
        /// 写入功能的数据库适配器
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public abstract class WriteableDatabaseAdapter<T> : DatabaseAdapter, IDatabaseWriteable<T> where T : new()
        {
            /// <summary>
            /// 新增前查询命令验证字符串，需查询结果数量=0时，方才添加
            /// </summary>
            /// <param name="tablec"></param>
            /// <returns></returns>
            protected abstract string appendSelelctStr(T tablec);
            /// <summary>
            /// 修改前查询命令字符串，需查询结果数量=1时，方才修改
            /// </summary>
            /// <param name="tablec"></param>
            /// <returns></returns>
            protected abstract string updateSelectStr(T tablec);
            /// <summary>
            /// 查找删除项命令字符串
            /// </summary>
            /// <param name="mode">搜索模式</param>
            /// <param name="value">搜索内容</param>
            /// <returns></returns>
            protected abstract string deleteSelectStr(int mode, string value);
            public bool Append(T obj)
            {
                var m = GetMySqlManager(appendSelelctStr(obj));
                return m.Add<T>(obj) == 1;
            }
            public bool Update(T tablec, string key, string value)
            {
                var m = GetMySqlManager(updateSelectStr(tablec));
                return m.Alter(m.CommandText, key, value) == 1;
            }

            public bool Delete(int mode, string value)
            {
                var m = GetMySqlManager(deleteSelectStr(mode, value));
                return m.DeleteAll() >= 0;
            }
        }
    }
}
